package demo14;

import java.util.Arrays;

/**
 * @program: qy158
 * @description:
 * @author: 闫克起2
 * @create: 2022-11-01 09:57
 **/
public class TestSafe {
    private static String [] arr=new String[2];
    private static int index=0;
    private static Object lock=new Object();
    public static void main(String[] args) throws InterruptedException {
        //构造函数中可以为线程提供任务对象Runnable
        //匿名实现类
        Thread t1=new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (lock) {
                    if (arr[index] == null) {
                        arr[index] = "hello";
                        index++;
                    }
                }
            }
        });

        Thread t2=new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (lock) {
                    if (arr[index] == null) {
                        arr[index] = "world";
                        index++;
                    }
                }
            }
        });

        t1.start();
        t2.start();

        //不能直接打印arr,因为main线程可能先获取cpu
        t1.join();
        t2.join();
        System.out.println(Arrays.toString(arr));
    }
}
